package com.zhou.framework.util;

import cn.hutool.core.codec.Base64;
import com.zhou.util.*;
import com.zhou.framework.exception.FileUploadException;
import com.zhou.message.dao.Attachment;
import lombok.SneakyThrows;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * @author lang.zhou
 * @since 2023/3/8 13:31
 */
public class FileUploaderUtil {

    public static String createPath(){
        String tempDir = SettingUtil.getTempDir();
        String uuid = StringTool.uuid();
        return tempDir + "/uploader/" + TimeUtil.formatNow("yyyyMMdd") + "/" + uuid;
    }

    public static String encodePath(String path){
        String uuid = Base64.encode(path);
        return EncryptUtil.encryptDES(uuid);
    }

    public static String decodePath(String uuid){
        String uuid1 = EncryptUtil.decryptDES(uuid);
        return Base64.decodeStr(uuid1);
    }

    public static File decodeFile(String uuid){
        String uuid1 = EncryptUtil.decryptDES(uuid);
        String path = Base64.decodeStr(uuid1);
        File file = new File(path);
        if(file.isFile()){
            return file;
        }
        throw new FileUploadException();
    }

    public static List<Attachment> decodeAttachments(Collection<String> ids){
        List<File> files = decodeFiles(ids);
        List<Attachment> l = new ArrayList<>(files.size());
        if(ObjectUtil.isNotEmpty(files)){
            for (File file : files) {
                l.add(file2Attach(file));
            }
        }
        return l;
    }

    @SneakyThrows
    public static Attachment file2Attach(File file){
        byte[] data = FileUtils.readFileToByteArray(file);
        String md5 = Md5Util.hex(data);
        Attachment attach = new Attachment();
        attach.setFile(data);
        attach.setFileName(FilenameUtils.getName(file.getName()));
        attach.setMd5(md5);
        attach.setIsPub(0);
        String prefix = FileUtil.getPrefix(file.getName());
        if(prefix != null){
            attach.setPrefix(prefix.toUpperCase());
        }
        attach.setSize((long) data.length);
        attach.setCreateDt(new Date());
        attach.setUpdateDt(attach.getCreateDt());
        return attach;
    }


    public static Attachment decodeAttachment(String uuid){
        File file = decodeFile(uuid);
        return file2Attach(file);
    }

    public static List<File> decodeFiles(Collection<String> ids){
        List<File> l = new ArrayList<>(2);
        if(ObjectUtil.isNotEmpty(ids)){
            for (String id : ids) {
                File file = decodeFile(id);
                l.add(file);
            }
        }
        return l;
    }

}
